<template>
<div>
  <div class="custom-tree-container">
    <el-tree
      :data="treeData"
      @node-click="getInfo"
      node-key="id"
      :default-expanded-keys="openKey"
      lazy
      :load="loadNode"
      style="width:40%;float:left;margin-right:5%;margin-top: 15px;">
      <span class="custom-tree-node" :class="{'colorccc':data.freezeFlag!=0}" slot-scope="{ node, data }">
        <span>{{ data.categoryName }}</span>
        <span v-if="data.freezeFlag!=0">（冻）</span>
        <span v-if="data.freezeFlag==0">
          <el-button
            type="text"
            size="mini"
            v-if="node.level===1"
            @click.stop="() => append(node.parent.data)">
            添加同级
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click.stop="() => appendChild(data)">
            添加子级
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="data.freezeFlag==0"
            @click.stop="() => freeze(node, data)">
            冻结
          </el-button>
           <el-button
              type="text"
              size="mini"
              @click.stop="() => edit(data)">
              编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click.stop="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-tabs v-model="activeName" @tab-click="changeTab" style="width:50%;float:left;">
      <template v-if="!!id"> 
      <el-tab-pane label="基本信息" name="info">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="fifty-ruleForm">
          <el-form-item style="text-align:right;width:100%;">
            <el-button type="primary" @click="()=>{isedit=!isedit;searchList()}" v-if="!isedit">取消</el-button>
            <el-button type="primary" @click="isedit=false" v-else>编辑</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" v-show="!isedit">保存</el-button>
          </el-form-item>
          <el-form-item label="节点名称">
            <el-input v-model="categoryName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="物料组" prop="materialGroupCode">
            <el-select v-model="ruleForm.materialGroupCode" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.MATERIAL_GROUP" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品组" prop="productGroupCode">
            <el-select v-model="ruleForm.productGroupCode" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.PRODUCT_GROUP" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>  
          <el-form-item label="税" prop="taxData">
            <el-input v-model="ruleForm.taxData" :disabled="isedit"></el-input>
          </el-form-item> 
          <el-form-item label="物料统计组" prop="materialStatisticsCode">
            <el-input v-model="ruleForm.materialStatisticsCode" :disabled="isedit"></el-input>
          </el-form-item> 
          <el-form-item label="物料定价组" prop="materialPricingGroup">
            <el-input v-model="ruleForm.materialPricingGroup" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="科目设置" prop="accountSet">
            <el-select v-model="ruleForm.accountSet" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.ACCOUNT_SET" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次管理" prop="batchFlag">
            <el-radio-group v-model="ruleForm.batchFlag" :disabled="isedit">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">不启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="收货到质检库存" prop="insmkFlag">
            <el-radio-group v-model="ruleForm.insmkFlag" :disabled="isedit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="采购周期（天）" prop="purchasingCycle">
            <el-input v-model="ruleForm.purchasingCycle" :disabled="isedit"></el-input>
          </el-form-item>  
          <el-form-item label="MRP类型" prop="mrpType">
            <el-select v-model="ruleForm.mrpType" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.MRP_TYPE" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="MRP控制者" prop="mrpMaster">
            <el-select v-model="ruleForm.mrpMaster" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.MRP_MASTER" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批量码" prop="batchCode">  
            <el-select v-model="ruleForm.batchCode" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.BATCH_CODE" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="反冲" prop="backlashFlag">
            <el-input v-model="ruleForm.backlashFlag" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="计划边际码" prop="plannedMarginalCode">
            <el-input v-model="ruleForm.plannedMarginalCode" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="可用性检查" prop="availabilityChecking">
            <el-input v-model="ruleForm.availabilityChecking" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="重复生产" prop="repeatProductFlag">
            <el-radio-group v-model="ruleForm.repeatProductFlag" :disabled="isedit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="重复生产参数文件" prop="repeatProductFlag">
            <el-input v-model="ruleForm.repeatProductFlag" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="生产调度员" prop="scheduler">
            <el-input v-model="ruleForm.scheduler" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="过帐到检验库存" prop="checkInventoryFlag">
            <el-radio-group v-model="ruleForm.checkInventoryFlag" :disabled="isedit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="价格控制" prop="priceControl">
            <el-select v-model="ruleForm.priceControl" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.PRICE_CONTROL" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="ML激活" prop="mlActivateFlag">
            <el-radio-group v-model="ruleForm.mlActivateFlag" :disabled="isedit">
              <el-radio :label="1">激活</el-radio>
              <el-radio :label="0">不激活</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="价格确定" prop="priceDecision">
            <el-select v-model="ruleForm.priceDecision" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.PRICE_CONFIRM" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="价格单位" prop="priceUnit">
            <el-input v-model="ruleForm.priceUnit" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="评估类" prop="evaluationClass">
            <el-select v-model="ruleForm.evaluationClass" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.MATERIAL_TYPE" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item> 
          <el-form-item label="移动平均价" prop="movingAvgPrice">
            <el-input v-model="ruleForm.movingAvgPrice" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="标准价" prop="standardPrice">
            <el-input v-model="ruleForm.standardPrice" :disabled="isedit"></el-input>
          </el-form-item>
          <el-form-item label="用QS的成本核算" prop="qsCostFlag">
            <el-radio-group v-model="ruleForm.qsCostFlag" :disabled="isedit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="物料来源" prop="materialSource">
            <el-select v-model="ruleForm.materialSource" placeholder="请选择" :disabled="isedit">
              <el-option label="X" value="0"></el-option>
              <el-option label="空" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料类型" prop="repeatProductParam">
            <el-select v-model="ruleForm.repeatProductParam" placeholder="请选择" :disabled="isedit">
              <el-option v-for="item in dicList.EVALUATION_TYPE" :key="item.id" :label="item.remarks" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="供应商信息" name="vendor">
         <el-table
          :data="vendorData"
          style="width: 100%">
          <el-table-column
            prop="vendorCode"
            label="供应商编码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="vendorErpCode"
            label="ERP代码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="vendorName"
            label="供应商名称">
          </el-table-column>
          <el-table-column
            prop="vendorLevel"
            label="供应商等级">
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="物料信息" name="material">
        <el-table
          :data="materialData"
          style="width: 100%">
          <el-table-column
            prop="materialGroupCode"
            label="组编码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="materialCode"
            label="物料编码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="materialName"
            label="物料名称">
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <div class="table-page" v-show="activeName!=='info'">
        <el-pagination
          background
          @size-change="changePage"
          @current-change="searchList"
          :current-page.sync="searchData.page"
          :page-sizes="[10, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
        </el-pagination>
      </div>
      </template>  
    </el-tabs>
  </div>

  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogShow"
    class="addtree-modal"
    width="600px"
    center>
    <div>
        <span><i>*</i>节点名称:</span>
        <el-input v-model="addTreeData.categoryName" placeholder="节点名称"></el-input>
    </div>  
    <div>
        <span><i>*</i>分类编码:</span>
        <el-input v-model="addTreeData.categoryCode" placeholder="分类编码"></el-input>
    </div>   
    <div>
        <span><i>*</i>核心品类标识 :</span>
         <el-radio-group v-model="addTreeData.coreFlag">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
    </div>  
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">取 消</el-button>
      <el-button type="primary" :disabled="!addTreeData.categoryName||!addTreeData.categoryCode" @click="addTree">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>
<script>
  export default {
    data() {
      return {
        dicKey:['MATERIAL_GROUP','PRODUCT_GROUP','ACCOUNT_SET','MRP_TYPE','MRP_MASTER','BATCH_CODE','PRICE_CONTROL','PRICE_CONFIRM','MATERIAL_TYPE','EVALUATION_TYPE'],
        dicList:{
          MATERIAL_GROUP:[],PRODUCT_GROUP:[],ACCOUNT_SET:[],MRP_TYPE:[],MRP_MASTER:[],BATCH_CODE:[],PRICE_CONTROL:[],PRICE_CONFIRM:[],MATERIAL_TYPE:[],EVALUATION_TYPE:[]
        },
        searchData:{
          page:1
        },
        pageTotal:0,
        dialogShow:false,
        addTreeData:{
          categoryName:'',
          parentId:'',
          coreFlag:1
        },
        isedit:true,
        dialogTitle:'',
        openKey:[],
        categoryName:'',
        ruleForm: {
          materialGroupCode:'',//物料组s
          productGroupCode:'',//产品组s
          materialStatisticsCode:'',//物料统计组t
          materialPricingGroup:'',//物料定价组t
          taxData:'',//税t
          accountSet:'',//科目设置s
          batchFlag:'',//批次管理r
          insmkFlag:'',//收货到质检库存r
          purchasingCycle:'',//采购周期（天）t
          mrpType:'',//MRP类型s
          mrpMaster:'',//MRP控制者s
          batchCode:'',//批量码s
          backlashFlag:'',//反冲t
          plannedMarginalCode:'',//计划边际码t
          availabilityChecking:'',//可用性检查t
          repeatProductFlag:'',//重复生产t
          scheduler:'',//生产调度员t
          checkInventoryFlag:'',//过帐到检验库存r
          priceControl:'',//价格控制s
          mlActivateFlag:'',//ML激活r
          priceDecision:'',//价格确定s
          priceUnit:'',//价格单位t
          evaluationClass:'',//评估类s
          movingAvgPrice:'',//移动平均价t
          standardPrice:'',//标准价t
          qsCostFlag:'',//用QS的成本核算r
          materialSource:'',//物料来源s
          repeatProductParam:'',//物料类型s
        },
        rules: {
          materialGroupCode: [ { required: true, message: '请选择物料组', trigger: 'change' }],
          productGroupCode: [ { required: true, message: '请选择产品组', trigger: 'change' }],
          taxData: [{ required: true, message: '请输入税', trigger: 'blur' }],
          materialStatisticsCode: [{ required: true, message: '请输入物料统计组', trigger: 'blur' }],
          materialPricingGroup: [{ required: true, message: '请输入物料定价组', trigger: 'blur' }],
          accountSet: [{ required: true, message: '请选择科目设置', trigger: 'change' }],
          batchFlag: [{ required: true, message: '请选择批次管理', trigger: 'change' }],
          insmkFlag: [{ required: false, message: '', trigger: 'change' }],
          purchasingCycle: [{ required: false, message: '', trigger: 'blur' }],
          mrpType: [{ required: true, message: '请选择MRP类型', trigger: 'change' }],
          mrpMaster: [{ required: true, message: '请选择MRP控制者', trigger: 'change' }],
          batchCode: [{ required: true, message: '请选择批量码', trigger: 'change' }],
          backlashFlag: [{ required: true, message: '请输入反冲', trigger: 'blur' }],
          plannedMarginalCode: [{ required: true, message: '请输入计划边际码', trigger: 'blur' }],
          availabilityChecking: [{ required: true, message: '请输入可用性检查', trigger: 'blur' }],
          repeatProductFlag: [{ required: false, message: '', trigger: 'blur' }],
          scheduler: [{ required: false, message: '', trigger: 'blur' }],
          checkInventoryFlag: [{ required: false, message: '', trigger: 'change' }],
          priceControl: [{ required: true, message: '请选择物价格控制', trigger: 'change' }],
          mlActivateFlag: [{ required: true, message: '请选择ML激活', trigger: 'change' }],
          priceDecision: [{ required: true, message: '请选择价格确定', trigger: 'change' }],
          priceUnit: [{ required: true, message: '请输入价格单位', trigger: 'blur' }],
          evaluationClass: [{ required: true, message: '请选择评估类', trigger: 'change' }],
          movingAvgPrice: [{ required: false, message: '', trigger: 'blur' }],
          standardPrice: [{ required: true, message: '请输入标准价', trigger: 'blur' }],
          qsCostFlag: [{ required: true, message: '请选择用QS的成本核算', trigger: 'change' }],
          materialSource: [{ required: true, message: '请选择物料来源', trigger: 'change' }],
          repeatProductParam: [{ required: true, message: '请选择物料类型', trigger: 'change' }]
        },
        treeData: [],
        materialData:[],
        vendorData:[],
        activeName:'info',
        id:'',
      }
    },
    created(){
      this.search();
      this.dicKey.forEach(val => {
        this.getDicData(val).then((data)=>{ 
          this.dicList[val]=data;
        });
      });
      console.log(this.dicList);
    },
    methods: {
      changePage(size){
        this.searchData.page=1;
        this.searchData.rows=size;
        this.transSearch();
      },
      searchList(){
        if(!this.id)return;
        if(this.activeName==='vendor'){
          this.axios.get(`${this.lib.config.host.masterData}/mdata/matCategorySrm/queryVendorByCategorySrmId/${this.id}`)
          .then((res)=> {
            this.vendorData=res.data.rows
          })
          .catch((error)=> {
            console.log(error);
          });
        }
        if(this.activeName==='material'){
          this.axios.post(`${this.lib.config.host.masterData}/mdata/material/query`,{categoryId:this.id})
          .then((res)=> {
            this.materialData=res.data.rows
          })
          .catch((error)=> {
            console.log(error);
          });
        }
        if(this.activeName==='info'){
          this.axios.get(`${this.lib.config.host.masterData}/mdata/matCategorySrm/getBaseInfoById/${this.id}`)
          .then((res)=> {
            this.resetForm('ruleForm');
            this.$nextTick(()=>{
              if(res.data){
                this.ruleForm=res.data
              }
            })
            this.isedit=true;
          })
          .catch((error)=> {
            console.log(error);
          });
        }
      },
      search(){
        this.dialogShow=false;
        this.axios.post(this.lib.config.host.masterData + "/mdata/matCategorySrm/query", {})
        .then((res)=> {
          this.treeData=res.data;
        })
        .catch((error)=> {
          console.log(error);
        });
      },
      loadNode(node, resolve) {
        if (node.level === 0) {
          return resolve([]);
        }
        this.axios.post(this.lib.config.host.masterData + "/mdata/matCategorySrm/query",{parentId:node.data.id})
        .then((res)=> {
           resolve(res.data);
        })
        .catch((error)=> {
          console.log(error);
        });
      },
      alertInit(mes){
        this.$message({
          type: 'success',
          message: mes
        });
      },
      alertError(mes){
        this.$message({
          type: 'error',
          message: mes
        });
      },
      append(data) {
        this.dialogTitle='添加同级';
        this.addTreeData={
          categoryName:'',
          categoryCode:'',
          coreFlag:1
        }
        this.dialogShow=true;
      },
      appendChild(data) {
        this.dialogTitle='添加子级';
        this.addTreeData={
          parentId:data.id,
          categoryName:'',
          categoryCode:'',
          coreFlag:1
        }
        this.addTree.parentId=data.id;
        this.dialogShow=true;
      },
      edit(data) {
        this.dialogTitle='编辑';
        this.addTreeData={
          id:data.id,
          categoryName:data.categoryName,
          categoryCode:data.categoryCode,
          coreFlag:data.coreFlag||1
        }
        this.dialogShow=true;
      },
      addTree(){
        this.axios.post(this.lib.config.host.masterData + "/mdata/matCategorySrm/addOrSaveCategory",this.addTreeData)
        .then((res)=> {
           this.alertInit( this.dialogTitle+'成功!')
          this.search();
        })
        .catch((error)=> {
          console.log(error);
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data={id:this.id,...this.ruleForm};
            console.log(data);
            this.axios.post(this.lib.config.host.masterData + "/mdata/matCategorySrm/saveOrUpdate",data)
            .then((res)=> {
              if(res.data.success){
                this.alertInit('已保存基本信息!');
                this.isedit=true;
              }else{
                this.alertError(res.data.message);
              }
            })
            .catch((error)=> {
              console.log(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      freeze(node, data) {
        this.$confirm('此操作将冻结该节点及其子节点, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.axios.get(`${this.lib.config.host.masterData}/mdata/matCategorySrm/freeze/${data.id}`)
          .then((res)=> {
            if(res.data.success){
              this.alertInit( '已冻结!');
              this.search();
            }else{
              this.alertError(res.data.message)
            }
          })
          .catch((error)=> {
            console.log(error);
          });
        }).catch(() => {
        });
      },
      remove(node, data) {
        this.$confirm('此操作将永久删除该节点及其子节点, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.axios.get(`${this.lib.config.host.masterData}/mdata/matCategorySrm/delete/${data.id}`)
          .then((res)=> {
            if(res.data.success){
              this.alertInit( '已删除!');
              this.search();
            }else{
              this.alertError(res.data.message)
            }
          })
          .catch((error)=> {
            console.log(error);
          });
        }).catch(() => {
        });
      },
      getInfo(data){
        this.activeName='info';
        this.isedit=true;
        if(this.openKey.some(val=>{return val===data.id})){
          this.openKey.splice(this.openKey.findIndex(val=>{return val===data.id}),1)
        }else{
          this.openKey.push(data.id)
        }
        this.id=data.id;
        this.categoryName=data.categoryName;
        this.searchList();
      },
      changeTab(){
        this.searchList();
      }
    }
  };
</script>

<style>
.colorccc{
  color:#ccc;
}
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .custom-tree-container {
    overflow: hidden;
  }
  .fifty-ruleForm .el-form-item{
    width: 50%;
    float: left;
  }
  .table-page{
    text-align: center;
    margin: 20px;
  }
 .addtree-modal .el-dialog__body div{
   margin:10px 0;
 } 
.addtree-modal .el-input{
  width: 80%;
}  
.v-modal{
  z-index: 999!important;
}
.addtree-modal{
  z-index: 1000!important;
}
.addtree-modal span i{
  color:red;
  margin:2px;
}  
</style>